package com.qubaopen.core.beans;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

/**
 * 与具体ORM实现无关的属性排序条件封装类.
 * 
 * PropertyOrder主要记录页面中简单的排序条件,比Hibernate的Criterion要简单.
 * 
 * 
 * @author ZhangYongYi
 */
public class PropertyOrder {
	public static final String ASC = "ASC";
	public static final String DESC = "DESC";
	public static final String STORE_PARAM_ORDERBY = "sort";

	private String orderBy;

	private String orderDir;

	public PropertyOrder(HttpServletRequest request) {
		String orderStr = request.getParameter(STORE_PARAM_ORDERBY);
		if (StringUtils.isNotEmpty(orderStr)) {
			JSONArray jsons = JSONArray.fromObject(orderStr);

			List<String> orderBys = new ArrayList<String>();
			List<String> orderDirs = new ArrayList<String>();
			JSONObject json = null;
			for (int i = 0; i < jsons.size(); i++) {
				json = jsons.getJSONObject(i);
				orderBys.add(json.getString("property"));
				orderDirs.add(json.getString("direction"));
			}

			this.orderBy = StringUtils.join(orderBys, ",");
			this.orderDir = StringUtils.join(orderDirs, ",");
		}
	}

	public PropertyOrder(String orderBy) {
		this.orderBy = orderBy;
		this.orderDir = ASC;
	}

	public PropertyOrder(String orderBy, String orderDir) {
		this.orderBy = orderBy;
		this.orderDir = orderDir;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	public String getOrderDir() {
		return orderDir;
	}

	public void setOrderDir(String orderDir) {
		this.orderDir = orderDir;
	}

}
